package com.wan.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wan.config.StaticImageConfig;
import com.wan.mapper.VegetableInfoMapper;
import entity.ResultBean;
import entity.common.BatchingInfo;
import entity.common.VegetableBatch;
import entity.common.VegetableDetails;
import entity.common.VegetableInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import utils.TimeUtils;
import utils.UUIDUtils;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 菜品表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-02-17
 */
@Slf4j
@Service
public class VegetableInfoService extends ServiceImpl<VegetableInfoMapper, VegetableInfo> {

    private static final String SEPARATOR = "/";
    private static final long FILE_SIZE = 1024*1024;

    @Autowired
    private VegetableDetailsService vegetableDetailsService;
    @Autowired
    private BatchingInfoService batchingInfoService;
    @Autowired
    private VegetableBatchService vegetableBatchService;

    @Autowired
    private StaticImageConfig staticImageConfig;

    @Value("${caipu.url}")
    private String url;

    public ResultBean uploadFile(MultipartFile file) {
        if (file == null) {
            return new ResultBean(500,"图片不能为空");
        }
        if (file.getSize() == 0 ){
            return new ResultBean(500,"图片不能为空");
        }
        if (file.getSize() > FILE_SIZE){
            return new ResultBean(500,"图片大小不能超过1M");
        }
        String uuid = UUIDUtils.getUUID();
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名{}==>"+fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String today = TimeUtils.GetNowDate("yyyy-MM-dd");
        String path = staticImageConfig.getUploadPath();
        //存储文件到磁盘
        StringBuilder dictPath = new StringBuilder();
        dictPath.append(path).append(today).append(SEPARATOR).append(uuid).append(suffix);

        File dictFile = new File(dictPath.toString());
        if(!dictFile.getParentFile().exists()) {
            dictFile.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dictFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean(500,"文件上传失败");
        }
        JSONObject jsonObject = new JSONObject();
        String src = url+today+SEPARATOR+uuid+suffix;
        jsonObject.put("src",src);

        return new ResultBean(0,"文件上传成功",jsonObject);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultBean saveVegetable(String title, String content, String[] ids, String imageFile, Double price, Double zkPrice,Integer count,Integer menuId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        VegetableInfo vegetableInfo = new VegetableInfo();
        vegetableInfo.setCreateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
        vegetableInfo.setCostPrice(price);
        String url = imageFile.substring(21);
        vegetableInfo.setImageUrl(url);
        vegetableInfo.setMenuId(menuId);
        vegetableInfo.setName(title);
        vegetableInfo.setPreferentialPrice(zkPrice);
        vegetableInfo.setStatus(0);
        vegetableInfo.setStock(count);
        vegetableInfo.setUsername(userDetails.getUsername());
        vegetableInfo.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
        Integer id = this.baseMapper.insert(vegetableInfo);
        if (id != null){
            VegetableDetails vegetableDetails = new VegetableDetails();
            vegetableDetails.setContent(content);
            vegetableDetails.setTitle(title);
            vegetableDetails.setCreateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
            vegetableDetails.setVegetableId(vegetableInfo.getId());
            vegetableDetails.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
            vegetableDetailsService.save(vegetableDetails);
            for (String batchId : ids) {
                Integer batchIdInt = Integer.parseInt(batchId);
                BatchingInfo batchingInfo = batchingInfoService.getById(batchIdInt);
                VegetableBatch vegetableBatch = new VegetableBatch();
                vegetableBatch.setBatchingId(Integer.parseInt(batchId));
                vegetableBatch.setBatchingName(batchingInfo.getBatchingName());
                vegetableBatch.setVegetableId(vegetableInfo.getId());
                vegetableBatch.setVegetableName(vegetableInfo.getName());
                vegetableBatch.setCreateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
                vegetableBatch.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
                vegetableBatchService.save(vegetableBatch);
            }
            return new ResultBean(200,"菜品上架成功");
        }else {
            return new ResultBean(500,"菜品上架失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultBean updateVegetable(Integer id,String title,String content, String[] ids, String imageFile, Double price, Double zkPrice, Integer count, Integer menuId) {
        if (id == null) {
            return new ResultBean(500,"菜品更新失败");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        VegetableInfo vegetableInfo = new VegetableInfo();
        vegetableInfo.setId(id);
        vegetableInfo.setCostPrice(price);
        String url = imageFile.substring(21);
        vegetableInfo.setImageUrl(url);
        vegetableInfo.setMenuId(menuId);
        vegetableInfo.setName(title);
        vegetableInfo.setPreferentialPrice(zkPrice);
        vegetableInfo.setStatus(0);
        vegetableInfo.setStock(count);
        vegetableInfo.setUsername(userDetails.getUsername());
        vegetableInfo.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
        Integer intId = this.baseMapper.updateById(vegetableInfo);
        if (intId != null){
            VegetableDetails vegetableDetails = new VegetableDetails();
            vegetableDetails.setContent(content);
            vegetableDetails.setTitle(title);
            vegetableDetails.setVegetableId(vegetableInfo.getId());
            vegetableDetails.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
            QueryWrapper<VegetableDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("vegetable_id",id);
            vegetableDetailsService.update(vegetableDetails,queryWrapper);
            QueryWrapper<VegetableBatch> queryWrapperQueryWrapper = new QueryWrapper<>();
            queryWrapperQueryWrapper.eq("vegetable_id",id);
            vegetableBatchService.remove(queryWrapperQueryWrapper);
            for (String batchId : ids) {
                Integer batchIdInt = Integer.parseInt(batchId);
                BatchingInfo batchingInfo = batchingInfoService.getById(batchIdInt);
                VegetableBatch vegetableBatch = new VegetableBatch();
                vegetableBatch.setBatchingId(Integer.parseInt(batchId));
                vegetableBatch.setBatchingName(batchingInfo.getBatchingName());
                vegetableBatch.setVegetableId(vegetableInfo.getId());
                vegetableBatch.setVegetableName(vegetableInfo.getName());
                vegetableBatch.setCreateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
                vegetableBatch.setUpdateTime(TimeUtils.GetNowDate("yyyy-MM-dd HH:mm:ss"));
                vegetableBatchService.save(vegetableBatch);
            }
            return new ResultBean(200,"菜品更新成功");
        }else {
            return new ResultBean(500,"菜品更新失败");
        }

    }
}
